<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<template>
  <div class="trace-stats-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>溯源统计</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="card-header">
            <span>总溯源码数量</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ stats.totalCodes || 0 }}</div>
            <div class="stat-text">个溯源码</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="card-header">
            <span>今日新增</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ stats.todayNewCodes || 0 }}</div>
            <div class="stat-text">个溯源码</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="card-header">
            <span>总查询次数</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ stats.totalQueries || 0 }}</div>
            <div class="stat-text">次</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div slot="header" class="card-header">
            <span>今日查询</span>
          </div>
          <div class="card-content">
            <div class="stat-number">{{ stats.todayQueries || 0 }}</div>
            <div class="stat-text">次</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>溯源查询趋势</span>
            <el-select v-model="queryTrendTimeRange" size="small" placeholder="选择时间范围">
              <el-option label="最近7天" value="7"></el-option>
              <el-option label="最近30天" value="30"></el-option>
              <el-option label="最近90天" value="90"></el-option>
            </el-select>
          </div>
          <div id="queryTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>溯源查询地区分布</span>
          </div>
          <div id="queryRegionChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>热门产品溯源排行</span>
          </div>
          <div id="productRankChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>设备类型分布</span>
          </div>
          <div id="deviceTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>浏览器分布</span>
          </div>
          <div id="browserChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>操作系统分布</span>
          </div>
          <div id="osChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近溯源查询记录 -->
    <el-card shadow="hover" class="recent-queries">
      <div slot="header" class="card-header">
        <span>最近溯源查询记录</span>
        <el-button size="small" type="primary" @click="refreshRecentQueries">刷新</el-button>
      </div>
      <el-table :data="recentQueries" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="traceCode" label="溯源码" width="180"></el-table-column>
        <el-table-column prop="productName" label="产品名称" width="180"></el-table-column>
        <el-table-column prop="location" label="查询地点" width="180"></el-table-column>
        <el-table-column prop="deviceType" label="设备类型" width="120"></el-table-column>
        <el-table-column prop="queryTime" label="查询时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.queryTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewTraceDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { traceStatsAPI } from '@/api/api';

export default {
  name: 'TraceStatsView',
  data() {
    return {
      loading: false,
      // 统计数据
      stats: {
        totalCodes: 0,
        todayNewCodes: 0,
        totalQueries: 0,
        todayQueries: 0
      },
      // 查询趋势时间范围
      queryTrendTimeRange: '7',
      // 最近查询记录
      recentQueries: [],
      // 图表实例
      charts: {
        queryTrend: null,
        queryRegion: null,
        productRank: null,
        deviceType: null,
        browser: null,
        os: null
      }
    };
  },
  created() {
    this.getTraceStats();
    this.getRecentQueries();
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.$nextTick(() => {
        this.initQueryTrendChart();
        this.initQueryRegionChart();
        this.initProductRankChart();
        this.initDeviceTypeChart();
        this.initBrowserChart();
        this.initOsChart();
      });
    },
    
    // 调整图表大小
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },
    
    // 初始化查询趋势图表
    initQueryTrendChart() {
      const chartDom = document.getElementById('queryTrendChart');
      if (!chartDom) return;
      
      this.charts.queryTrend = echarts.init(chartDom);
      this.loadQueryTrendData();
    },
    
    // 初始化地区分布图表
    initQueryRegionChart() {
      const chartDom = document.getElementById('queryRegionChart');
      if (!chartDom) return;
      
      this.charts.queryRegion = echarts.init(chartDom);
      this.loadQueryRegionData();
    },
    
    // 初始化产品排行图表
    initProductRankChart() {
      const chartDom = document.getElementById('productRankChart');
      if (!chartDom) return;
      
      this.charts.productRank = echarts.init(chartDom);
      this.loadProductRankData();
    },
    
    // 初始化设备类型图表
    initDeviceTypeChart() {
      const chartDom = document.getElementById('deviceTypeChart');
      if (!chartDom) return;
      
      this.charts.deviceType = echarts.init(chartDom);
      this.loadDeviceTypeData();
    },
    
    // 初始化浏览器分布图表
    initBrowserChart() {
      const chartDom = document.getElementById('browserChart');
      if (!chartDom) return;
      
      this.charts.browser = echarts.init(chartDom);
      this.loadBrowserData();
    },
    
    // 初始化操作系统分布图表
    initOsChart() {
      const chartDom = document.getElementById('osChart');
      if (!chartDom) return;
      
      this.charts.os = echarts.init(chartDom);
      this.loadOsData();
    },
    
    // 获取基本统计数据
    async getTraceStats() {
      try {
        this.loading = true;
        const response = await traceStatsAPI.getBasicStats();
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            this.stats = response.data.data;
          } else {
            this.stats = response.data;
          }
          
          // 确保必要的字段存在
          if (!this.stats || typeof this.stats !== 'object') {
            console.error('基本统计数据格式不正确:', this.stats);
            throw new Error('数据格式不正确');
          }
          
          // 确保所有必要的字段都有默认值
          this.stats = {
            totalCodes: this.stats.totalCodes || 0,
            todayNewCodes: this.stats.todayNewCodes || 0,
            totalQueries: this.stats.totalQueries || 0,
            todayQueries: this.stats.todayQueries || 0
          };
        } else {
          // 模拟数据
          this.stats = {
            totalCodes: 1256,
            todayNewCodes: 42,
            totalQueries: 8765,
            todayQueries: 312
          };
          console.log('使用模拟的统计数据');
        }
        
        this.loading = false;
      } catch (error) {
        console.error('获取统计数据失败:', error);
        // 模拟数据
        this.stats = {
          totalCodes: 1256,
          todayNewCodes: 42,
          totalQueries: 8765,
          todayQueries: 312
        };
        this.loading = false;
      }
    },
    
    // 获取最近查询记录
    async getRecentQueries() {
      try {
        this.loading = true;
        const response = await traceStatsAPI.getRecentQueries();
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            this.recentQueries = response.data.data;
          } else {
            this.recentQueries = response.data;
          }
          
          // 确保recentQueries是数组
          if (!Array.isArray(this.recentQueries)) {
            console.error('最近查询记录数据格式不正确:', this.recentQueries);
            throw new Error('数据格式不正确');
          }
        } else {
          // 模拟数据
          this.recentQueries = [
            {
              id: 1,
              traceCode: 'TR202503250001',
              productName: '宁夏中宁枸杞精选',
              location: '北京市',
              deviceType: '手机',
              queryTime: new Date().toISOString()
            },
            {
              id: 2,
              traceCode: 'TR202503250023',
              productName: '有机红枸杞',
              location: '上海市',
              deviceType: '平板',
              queryTime: new Date(Date.now() - 3600000).toISOString()
            },
            {
              id: 3,
              traceCode: 'TR202503240015',
              productName: '黑枸杞礼盒装',
              location: '广州市',
              deviceType: '电脑',
              queryTime: new Date(Date.now() - 7200000).toISOString()
            }
          ];
          console.log('使用模拟的最近查询记录');
        }
        
        this.loading = false;
      } catch (error) {
        console.error('获取最近查询记录失败:', error);
        // 模拟数据
        this.recentQueries = [
          {
            id: 1,
            traceCode: 'TR202503250001',
            productName: '宁夏中宁枸杞精选',
            location: '北京市',
            deviceType: '手机',
            queryTime: new Date().toISOString()
          },
          {
            id: 2,
            traceCode: 'TR202503250023',
            productName: '有机红枸杞',
            location: '上海市',
            deviceType: '平板',
            queryTime: new Date(Date.now() - 3600000).toISOString()
          }
        ];
        this.loading = false;
      }
    },
    
    // 加载查询趋势数据
    async loadQueryTrendData() {
      try {
        const response = await traceStatsAPI.getQueryTrend(this.queryTrendTimeRange);
        let data;
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            data = response.data.data;
          } else {
            data = response.data;
          }
          
          // 检查数据格式是否正确
          if (!data.dates || !data.values || !Array.isArray(data.dates) || !Array.isArray(data.values)) {
            console.error('查询趋势数据格式不正确:', data);
            throw new Error('数据格式不正确');
          }
        } else {
          // 模拟数据
          const days = parseInt(this.queryTrendTimeRange);
          data = {
            dates: Array.from({ length: days }, (_, i) => {
              const date = new Date();
              date.setDate(date.getDate() - (days - 1 - i));
              return `${date.getMonth() + 1}月${date.getDate()}日`;
            }),
            values: Array.from({ length: days }, () => Math.floor(Math.random() * 100) + 20)
          };
          console.log('使用模拟的查询趋势数据');
        }
        
        // 更新趋势图表
        this.charts.queryTrend.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.dates,
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '查询次数',
              type: 'line',
              smooth: true,
              data: data.values,
              itemStyle: {
                color: '#409EFF'
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: 'rgba(64, 158, 255, 0.7)'
                    },
                    {
                      offset: 1,
                      color: 'rgba(64, 158, 255, 0.1)'
                    }
                  ]
                }
              }
            }
          ]
        });
      } catch (error) {
        console.error('加载查询趋势数据失败:', error);
        // 显示默认图表
        this.charts.queryTrend.setOption({
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: [45, 62, 38, 78, 56, 86, 95],
              type: 'line',
              smooth: true
            }
          ]
        });
      }
    },
    
    // 加载地区分布数据
    async loadQueryRegionData() {
      try {
        const response = await traceStatsAPI.getQueryRegionDistribution();
        let data;
        
        if (response && response.data && Array.isArray(response.data)) {
          data = response.data;
        } else if (response && response.data && response.data.success && Array.isArray(response.data.data)) {
          // 处理包含在ApiResponse中的数据
          data = response.data.data;
        } else {
          // 模拟数据
          data = [
            { name: '北京', value: 135 },
            { name: '上海', value: 120 },
            { name: '广州', value: 98 },
            { name: '深圳', value: 86 },
            { name: '杭州', value: 72 },
            { name: '成都', value: 65 },
            { name: '武汉', value: 53 },
            { name: '西安', value: 48 },
            { name: '南京', value: 42 },
            { name: '重庆', value: 38 }
          ];
          console.log('使用模拟的地区分布数据');
        }
        
        // 确保数据格式正确
        if (!Array.isArray(data)) {
          console.error('地区分布数据格式不正确', data);
          throw new Error('数据格式不正确');
        }
        
        // 确保每个项目都有name和value属性
        data = data.map(item => {
          if (typeof item === 'object' && item !== null) {
            return {
              name: item.name || '未知',
              value: item.value || 0
            };
          } else {
            return { name: '未知', value: 0 };
          }
        });
        
        // 更新地区分布图表
        this.charts.queryRegion.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '查询次数',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: data
            }
          ]
        });
      } catch (error) {
        console.error('加载地区分布数据失败:', error);
        // 显示默认图表
        this.charts.queryRegion.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [
            {
              name: '查询次数',
              type: 'pie',
              radius: ['50%', '70%'],
              data: [
                { value: 135, name: '北京' },
                { value: 120, name: '上海' },
                { value: 98, name: '广州' },
                { value: 86, name: '深圳' },
                { value: 72, name: '杭州' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    
    // 加载产品排行数据
    async loadProductRankData() {
      try {
        const response = await traceStatsAPI.getProductQueryRanking();
        let data;
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            data = response.data.data;
          } else {
            data = response.data;
          }
          
          // 确保数据格式正确
          if (!Array.isArray(data)) {
            console.error('产品排行数据格式不正确:', data);
            throw new Error('数据格式不正确');
          }
          
          // 确保每个项目都有name和value属性
          data = data.map(item => {
            if (typeof item === 'object' && item !== null) {
              return {
                name: item.name || '未知产品',
                value: item.value || 0
              };
            } else {
              return { name: '未知产品', value: 0 };
            }
          });
        } else {
          // 模拟数据
          data = [
            { name: '宁夏中宁枸杞精选', value: 256 },
            { name: '有机红枸杞', value: 213 },
            { name: '黑枸杞礼盒装', value: 187 },
            { name: '枸杞芽茶', value: 145 },
            { name: '枸杞干果礼盒', value: 124 },
            { name: '其他产品', value: 92 }
          ];
          console.log('使用模拟的产品排行数据');
        }
        
        // 产品名称
        const productNames = data.map(item => item.name);
        // 查询次数
        const values = data.map(item => item.value);
        
        // 更新产品排行图表
        this.charts.productRank.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: productNames,
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                if (value.length > 10) {
                  return value.substring(0, 10) + '...';
                }
                return value;
              }
            }
          },
          series: [
            {
              name: '查询次数',
              type: 'bar',
              data: values,
              itemStyle: {
                color: function(params) {
                  // 颜色渐变
                  const colorList = [
                    '#67C23A', '#91CC75', '#E6A23C', '#F56C6C', '#909399', '#C4C4C4'
                  ];
                  return colorList[params.dataIndex % colorList.length];
                }
              }
            }
          ]
        });
      } catch (error) {
        console.error('加载产品排行数据失败:', error);
        // 显示默认图表
        this.charts.productRank.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: ['宁夏中宁枸杞精选', '有机红枸杞', '黑枸杞礼盒装', '枸杞芽茶', '枸杞干果礼盒']
          },
          series: [
            {
              name: '查询次数',
              type: 'bar',
              data: [256, 213, 187, 145, 124]
            }
          ]
        });
      }
    },
    
    // 加载设备类型数据
    async loadDeviceTypeData() {
      try {
        const response = await traceStatsAPI.getDeviceTypeDistribution();
        let data;
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            data = response.data.data;
          } else {
            data = response.data;
          }
          
          // 确保数据格式正确
          if (!Array.isArray(data)) {
            console.error('设备类型数据格式不正确:', data);
            throw new Error('数据格式不正确');
          }
          
          // 确保每个项目都有name和value属性
          data = data.map(item => {
            if (typeof item === 'object' && item !== null) {
              return {
                name: item.name || '未知设备',
                value: item.value || 0
              };
            } else {
              return { name: '未知设备', value: 0 };
            }
          });
        } else {
          // 模拟数据
          data = [
            { name: '手机', value: 680 },
            { name: '平板', value: 128 },
            { name: '电脑', value: 95 },
            { name: '其他', value: 38 }
          ];
          console.log('使用模拟的设备类型数据');
        }
        
        // 更新设备类型图表
        this.charts.deviceType.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '设备类型',
              type: 'pie',
              radius: '60%',
              center: ['40%', '50%'],
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      } catch (error) {
        console.error('加载设备类型数据失败:', error);
        // 显示默认图表
        this.charts.deviceType.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [
            {
              name: '设备类型',
              type: 'pie',
              radius: '60%',
              data: [
                { value: 680, name: '手机' },
                { value: 128, name: '平板' },
                { value: 95, name: '电脑' },
                { value: 38, name: '其他' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    
    // 加载浏览器分布数据
    async loadBrowserData() {
      try {
        const response = await traceStatsAPI.getBrowserDistribution();
        let data;
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            data = response.data.data;
          } else {
            data = response.data;
          }
          
          // 确保数据格式正确
          if (!Array.isArray(data)) {
            console.error('浏览器分布数据格式不正确:', data);
            throw new Error('数据格式不正确');
          }
          
          // 确保每个项目都有name和value属性
          data = data.map(item => {
            if (typeof item === 'object' && item !== null) {
              return {
                name: item.name || '未知浏览器',
                value: item.value || 0
              };
            } else {
              return { name: '未知浏览器', value: 0 };
            }
          });
        } else {
          // 模拟数据
          data = [
            { name: 'Chrome', value: 450 },
            { name: 'Safari', value: 200 },
            { name: '微信浏览器', value: 150 },
            { name: 'Firefox', value: 100 },
            { name: 'Edge', value: 80 },
            { name: '其他', value: 50 }
          ];
          console.log('使用模拟的浏览器分布数据');
        }
        
        // 更新浏览器分布图表
        this.charts.browser.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '浏览器',
              type: 'pie',
              radius: '60%',
              center: ['40%', '50%'],
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      } catch (error) {
        console.error('加载浏览器分布数据失败:', error);
        // 显示默认图表
        this.charts.browser.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [
            {
              name: '浏览器',
              type: 'pie',
              radius: '60%',
              data: [
                { value: 450, name: 'Chrome' },
                { value: 200, name: 'Safari' },
                { value: 150, name: '微信浏览器' },
                { value: 100, name: 'Firefox' },
                { value: 80, name: 'Edge' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    
    // 加载操作系统分布数据
    async loadOsData() {
      try {
        const response = await traceStatsAPI.getOsDistribution();
        let data;
        
        if (response && response.data) {
          // 判断数据是否是直接的对象或者包装在success/data中
          if (response.data.success !== undefined && response.data.data) {
            data = response.data.data;
          } else {
            data = response.data;
          }
          
          // 确保数据格式正确
          if (!Array.isArray(data)) {
            console.error('操作系统分布数据格式不正确:', data);
            throw new Error('数据格式不正确');
          }
          
          // 确保每个项目都有name和value属性
          data = data.map(item => {
            if (typeof item === 'object' && item !== null) {
              return {
                name: item.name || '未知操作系统',
                value: item.value || 0
              };
            } else {
              return { name: '未知操作系统', value: 0 };
            }
          });
        } else {
          // 模拟数据
          data = [
            { name: 'Windows', value: 400 },
            { name: 'Android', value: 300 },
            { name: 'iOS', value: 280 },
            { name: 'macOS', value: 120 },
            { name: '其他', value: 40 }
          ];
          console.log('使用模拟的操作系统分布数据');
        }
        
        // 更新操作系统分布图表
        this.charts.os.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: data.map(item => item.name)
          },
          series: [
            {
              name: '操作系统',
              type: 'pie',
              radius: '60%',
              center: ['40%', '50%'],
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      } catch (error) {
        console.error('加载操作系统分布数据失败:', error);
        // 显示默认图表
        this.charts.os.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [
            {
              name: '操作系统',
              type: 'pie',
              radius: '60%',
              data: [
                { value: 400, name: 'Windows' },
                { value: 300, name: 'Android' },
                { value: 280, name: 'iOS' },
                { value: 120, name: 'macOS' },
                { value: 40, name: '其他' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      }
    },
    
    // 刷新最近查询记录
    refreshRecentQueries() {
      this.getRecentQueries();
    },
    
    // 查看溯源详情
    viewTraceDetail(row) {
      this.$router.push({
        path: '/trace/detail',
        query: { code: row.traceCode }
      });
    },
    
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 时间范围变化处理
    watchQueryTrendTimeRange(newValue) {
      this.loadQueryTrendData();
    }
  },
  watch: {
    queryTrendTimeRange: 'watchQueryTrendTimeRange'
  }
}
</script>

<style scoped>
.trace-stats-container {
  padding: 20px;
}

.stat-cards {
  margin-top: 20px;
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 10px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-text {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.recent-queries {
  margin-bottom: 20px;
}
</style> 